<template>
  <div id="el-fence-draw">
    <el-divider>电子围栏</el-divider>
    <!--    <img :src="imgUrl" alt="">-->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-select v-model="cameraID" placeholder="请选择摄像头">
          <el-option value="1" label="1号摄像头" />
          <el-option value="2" label="2号摄像头" />
          <el-option value="3" label="3号摄像头" />
          <el-option value="4" label="4号摄像头" />
        </el-select>
        <el-button style="margin-left: 10px; margin-top: 10px;" type="primary" @click="dataInit()">获取数据</el-button>
        <el-button style="margin-left: 10px; margin-top: 10px;" type="warning" @click="resetCanvas()">复原</el-button>
        <el-form ref="form" style="margin-top: 20px; margin-left: 10px">
          <el-form-item label="选择颜色">
            <el-select v-model="form.color" placeholder="请选择颜色">
              <el-option value="#e30e0e" label="红色" />
              <el-option value="#133cc4" label="蓝色" />
              <el-option value="#19e013" label="绿色" />
            </el-select>
          </el-form-item>
          <el-form-item label="画线类型">
            <el-tooltip class="item" effect="dark" content="矩形面从左往右划取,只能画一个" placement="top">
              <el-select v-model="form.type" placeholder="请选择颜色">
                <el-option value="line" label="线" />
                <el-option value="rect" label="矩形面" />
              </el-select>
            </el-tooltip>
          </el-form-item>
        </el-form>
        <el-button style="margin-left: 10px" type="success" @click="btnUpload()">上传数据</el-button>
        <!--        说明列表-->
        <el-table
          :data="tableData"
          stripe
          style="width: 100%"
          align="center"
        >
          <el-table-column
            prop="color"
            label="颜色"
            width="120"
            align="center"
          >
            <template v-slot="scope">
              <el-tag
                :type="colorType(scope.row.color)"
                disable-transitions
              >{{ scope.row.color }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="message"
            label="颜色作用"
            align="center"
          />
        </el-table>
      </el-col>
      <el-col :span="18">
        <canvas
          v-if="canvas"
          id="canvas"
          :width="imgWidth"
          :height="imgHeight"
          @mousedown="canvasDown($event)"
          @mousemove="canvasMove($event)"
          @mouseup="canvasUp($event)"
        />
        <el-empty v-else />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getFenceImg, getFenceImgCamera, postFenceList } from '@/api/fence'
import { BASE_DETECT_URL } from '@/api/realTime'
import debounce from 'lodash.debounce'

export default {
  name: 'ElFenceDraw',
  data() {
    return {
      canvas: false,
      canvasStart: false,
      tableData: [{
        color: '红色',
        message: '发出离岗警报'
      }, {
        color: '蓝色',
        message: '接近围栏警报'
      }, {
        color: '绿色',
        message: '发出入侵警告'
      }],
      imgUrl: '',
      context: {},
      imgWidth: 500,
      imgHeight: 500,
      moving: false,
      moveStep: 0,
      rectPos: {
        left: 0,
        top: 0,
        width: 0,
        height: 0
      },
      tempImgData: null,
      tempColor: '',
      moveX: 0,
      moveY: 0,
      toX: 0,
      toY: 0,
      lineArray: [],
      colorArray: [],
      pointArray: [],
      lineIndex: [],
      lineList: [],
      form: {
        color: '#133cc4',
        type: 'rect'
      },
      cameraID: '1',
      rect: {
        rightTopX: 0,
        rightTopY: 0,
        rightBottomX: 0,
        rightBottomY: 0,
        leftBottomX: 0,
        leftBottomY: 0
      },
      rectError: false
    }
  },
  watch: {
    'form.type': {
      handler() {
        this.resetCanvas()
        this.lineArray = []
        this.dataInit()
      },
      immediate: false,
      deep: true
    }
  },
  methods: {
    colorType(color) {
      if (color === '红色') {
        return 'danger'
      } else if (color === '蓝色') {
        return 'primary'
      } else if (color === '绿色') {
        return 'success'
      }
    },
    // 获取数据
    async dataInit() {
      this.rectError = false
      this.canvas = true
      // 获取服务器图片
      if (!this.$store.getters.useVideo) {
        const { URL } = await getFenceImg()
        this.imgUrl = BASE_DETECT_URL + URL
        console.log(this.imgUrl)
        console.log('img')
      } else {
        if (this.cameraID === '1') {
          console.log(1)
          const { URL } = await getFenceImgCamera(this.$store.state.camera.camera1.url)
          this.imgUrl = BASE_DETECT_URL + URL
        } else if (this.cameraID === '2') {
          const { URL } = await getFenceImgCamera(this.$store.state.camera.camera2.url)
          this.imgUrl = BASE_DETECT_URL + URL
        } else if (this.cameraID === '3') {
          const { URL } = await getFenceImgCamera(this.$store.state.camera.camera3.url)
          this.imgUrl = BASE_DETECT_URL + URL
        } else {
          const { URL } = await getFenceImgCamera(this.$store.state.camera.camera4.url)
          this.imgUrl = BASE_DETECT_URL + URL
        }
        console.log(this.imgUrl)
        console.log('camera')
      }
      // 获取本地测试图片
      // this.imgUrl = 'http://localhost:9528/test.png'
      // 获取图片尺寸
      const imgSize = this.getImgSize(this.imgUrl)
      imgSize.then((result) => {
        console.log(result)
        this.imgWidth = result.width
        this.imgHeight = result.height
      })
      this.initCanvas()
    },
    // 初始化
    initCanvas() { // 初始化
      this.canvasStart = true
      // 初始化canvas
      const canvas = document.querySelector('#canvas')
      this.context = canvas.getContext('2d')
      // console.log(canvas.getBoundingClientRect())
      const rect = canvas.getBoundingClientRect()
      this.rectPos.left = rect.left
      this.rectPos.top = rect.top
      this.rectPos.width = rect.width
      this.rectPos.height = rect.height
      // 84test
      this.context.lineWidth = 1
      this.context.shadowBlur = 1
      this.context.shadowColor = '#2c3e50'
      this.context.strokeStyle = '#2c3e50'
      const bgImg = new Image()
      bgImg.src = this.imgUrl
      bgImg.crossOrigin = ''
      bgImg.onload = () => {
        this.context.drawImage(bgImg, 0, 0)
      }
      // this.context.drawImage(bgImg, 0, 0)
    },
    // 清空画布
    resetCanvas() {
      this.context.fillStyle = '#fff'
      this.context.clearRect(0, 0, this.imgWidth, this.imgHeight)
      this.context.fillRect(0, 0, this.imgWidth, this.imgHeight)
      this.context.fillStyle = '#000'
      this.lineArray = []
      this.pointArray = []
      this.lineIndex = []
      this.colorArray = []
      this.lineList = []
      this.canvasStart = false
      this.canvas = false
      this.rectError = false
    },
    // 获取图片尺寸
    getImgSize(url) {
      return new Promise((resolve, reject) => {
        const imgObj = new Image()
        imgObj.src = url
        imgObj.onload = () => {
          resolve({
            width: imgObj.width,
            height: imgObj.height
          })
        }
      })
    },
    // 鼠标点击事件
    canvasDown(e) {
      this.rectError = false
      if (this.form.type === 'line') {
        // 红色
        // this.context.strokeStyle = '#e30e0e'
        // 蓝色
        this.context.strokeStyle = this.form.color
        this.moving = true
        // this.context.lineTo(100, 100)
        // this.context.stroke()
        const x = e.offsetX
        const y = e.offsetY
        console.log('x:' + x, 'y:' + y)
        this.moveX = e.offsetX
        this.moveY = e.offsetY
      } else if (this.form.type === 'rect') {
        this.context.strokeStyle = this.form.color
        this.moving = true
        this.moveX = e.offsetX
        this.moveY = e.offsetY
      }
    },
    canvasMove(e) {
      if (this.form.type === 'line') {
        if (this.moving === true && this.canvasStart === true) {
          // this.context.clearRect(0, 0, this.imgWidth, this.imgHeight)
          const bgImg = new Image()
          bgImg.src = this.imgUrl
          bgImg.crossOrigin = ''
          this.context.drawImage(bgImg, 0, 0)
          for (let i = 0; i < this.lineArray.length; i++) {
            if (this.lineArray[i][4] === '#e30e0e') {
              this.context.strokeStyle = '#e30e0e'
            } else if (this.lineArray[i][4] === '#133cc4') {
              this.context.strokeStyle = '#133cc4'
            } else {
              this.context.strokeStyle = '#19e013'
            }
            this.reDrawLine(this.lineArray[i][0], this.lineArray[i][1], this.lineArray[i][2], this.lineArray[i][3])
          }
          this.context.strokeStyle = this.form.color
          this.drawLine(e)
        }
      } else if (this.form.type === 'rect') {
        if (this.moving === true && this.canvasStart === true) {
          const bgImg = new Image()
          bgImg.src = this.imgUrl
          bgImg.crossOrigin = ''
          this.context.drawImage(bgImg, 0, 0)
          for (let i = 0; i < this.lineArray.length; i++) {
            if (this.lineArray[i][4] === '#e30e0e') {
              this.context.strokeStyle = '#e30e0e'
            } else if (this.lineArray[i][4] === '#133cc4') {
              this.context.strokeStyle = '#133cc4'
            } else {
              this.context.strokeStyle = '#19e013'
            }
            this.reDrawRect(this.lineArray[i][0], this.lineArray[i][1], this.lineArray[i][2], this.lineArray[i][3])
          }
          this.context.strokeStyle = this.form.color
          this.drawRect(e)
        }
      }
    },
    canvasUp(e) {
      if (this.form.type === 'line') {
        this.moving = false
        this.pointArray.push([this.moveX, this.moveY], [this.toX, this.toY])
        console.log(this.pointArray)
        const indexP = this.findIndex(this.pointArray, this.toX)
        console.log('toX:' + this.toX)
        this.lineIndex.push(indexP)
        console.log('lineIndex:' + this.lineIndex)
        this.lineList.push(this.computerKB(this.moveX, this.moveY, this.toX, this.toY))
        console.log(this.lineList)
        // this.lineIndex.push(indexP)
        // console.log('lineIndex:' + this.lineIndex)
        if (this.form.color === '#e30e0e') {
          this.colorArray.push(2)
          this.tempColor = '#e30e0e'
        } else if (this.form.color === '#133cc4') {
          this.colorArray.push(0)
          this.tempColor = '#133cc4'
        } else {
          this.colorArray.push(1)
          this.tempColor = '#19e013'
        }
        console.log('ColorArray:' + this.colorArray)
        this.lineArray.push([this.moveX, this.moveY, this.toX, this.toY, this.tempColor])
        console.log('lineArray:' + this.lineArray)
        this.toX = 0
        this.toY = 0
        this.moveY = 0
        this.moveX = 0
      } else if (this.form.type === 'rect') {
        // 颜色
        if (this.form.color === '#e30e0e') {
          this.colorArray.push(2, 2, 2, 2)
          this.tempColor = '#e30e0e'
        } else if (this.form.color === '#133cc4') {
          this.colorArray.push(0, 0, 0, 0)
          this.tempColor = '#133cc4'
        } else {
          this.colorArray.push(1, 1, 1, 1)
          this.tempColor = '#19e013'
        }
        console.log(this.colorArray)
        // lineArray为了存储矩形的历史记录 非传递后端数据
        if (this.rectError === false) {
          this.lineArray.push([this.moveX, this.moveY, this.toX, this.toY, this.tempColor])
        }
        // pointArray 线段坐标
        const rightTopX = this.moveX + (this.toX - this.moveX)
        const rightTopY = this.moveY
        const rightBottomX = this.moveX + (this.toX - this.moveX)
        const rightBottomY = this.moveY + (this.toY - this.moveY)
        const leftBottomX = this.moveX
        const leftBottomY = this.moveY + (this.toY - this.moveY)
        this.pointArray.push([this.moveX, this.moveY], [rightTopX, rightTopY], [rightBottomX, rightBottomY], [leftBottomX, leftBottomY])
        console.log(this.pointArray)
        // lineIndex 线段索引
        const indexP1 = this.findRectIndex(this.pointArray, [rightTopX, rightTopY])
        const indexP2 = this.findRectIndex(this.pointArray, [rightBottomX, rightBottomY])
        const indexP3 = this.findRectIndex(this.pointArray, [leftBottomX, leftBottomY])
        const indexP4 = this.findRectIndex(this.pointArray, [this.moveX, this.moveY])
        this.lineIndex.push(indexP1, indexP2, indexP3, indexP4)
        console.log(this.lineIndex)
        // 线段斜率
        // this.lineList.push(this.computerKB(this.moveX, this.moveY, this.toX, this.toY))
        const line1 = this.computerKB(this.moveX, this.moveY, rightTopX, rightTopY)
        const line2 = this.computerKB(rightTopX, rightTopY, rightBottomX, rightBottomY)
        const line3 = this.computerKB(rightBottomX, rightBottomY, leftBottomX, leftBottomY)
        const line4 = this.computerKB(leftBottomX, leftBottomY, this.moveX, this.moveY)
        this.lineList.push(line1, line2, line3, line4)
        console.log(this.lineList)
        // 重置
        this.moving = false
        this.toX = 0
        this.toY = 0
        this.moveY = 0
        this.moveX = 0
        this.rect.leftBottomX = 0
        this.rect.leftBottomY = 0
        this.rect.rightTopX = 0
        this.rect.rightTopY = 0
        this.rect.rightBottomX = 0
        this.rect.rightBottomY = 0
      }
    },
    // 画线
    drawLine(e) {
      if (this.moving) {
        this.toX = e.offsetX
        this.toY = e.offsetY
        this.context.beginPath()
        this.context.moveTo(this.moveX, this.moveY)
        this.context.lineTo(this.toX, this.toY)
        this.context.closePath()
        this.context.stroke()
      }
    },
    // 画矩形
    drawRect(e) {
      if (this.moving) {
        this.toX = e.offsetX
        this.toY = e.offsetY
        if (this.toX - this.moveX >= 0 && this.toY - this.moveY >= 0) {
          this.context.beginPath()
          this.context.rect(this.moveX, this.moveY, this.toX - this.moveX, this.toY - this.moveY)
          this.context.closePath()
          this.context.stroke()
        } else {
          this.drawRectError()
          this.rectError = true
        }
      }
    },
    reDrawLine(moveX, moveY, toX, toY) {
      this.context.beginPath()
      this.context.moveTo(moveX, moveY)
      this.context.lineTo(toX, toY)
      this.context.closePath()
      this.context.stroke()
    },
    reDrawRect(moveX, moveY, toX, toY) {
      this.context.beginPath()
      this.context.rect(moveX, moveY, toX - moveX, toY - moveY)
      this.context.closePath()
      this.context.stroke()
    },
    findIndex(array, target) {
      for (let i = 0; i < array.length; i++) {
        const i2 = array[i].indexOf(target)
        if (i2 !== -1) {
          return i
        }
      }
      return undefined
    },
    findRectIndex(array, target) {
      for (const [i, arr] of array.entries()) {
        if (arr.toString() === target.toString()) {
          return i
        }
      }
    },
    computerKB(x1, y1, x2, y2) {
      const k = (y2 - y1) / (x2 - x1)
      const b = (-k * x1) + y1
      if (k > 15 || k < -15) {
        return [x2]
      }
      return [k, b]
    },
    async btnUpload() {
      let monitor_id = ''
      let new_monitor_flag_data = 0
      if (this.$store.getters.useVideo) {
        if (this.cameraID === '1') {
          monitor_id = this.$store.state.camera.camera1.url
          new_monitor_flag_data = this.$store.state.camera.camera1.monitor_flag
        } else if (this.cameraID === '2') {
          monitor_id = this.$store.state.camera.camera2.url
          new_monitor_flag_data = this.$store.state.camera.camera2.monitor_flag
        } else if (this.cameraID === '3') {
          monitor_id = this.$store.state.camera.camera3.url
          new_monitor_flag_data = this.$store.state.camera.camera3.monitor_flag
        } else if (this.cameraID === '4') {
          monitor_id = this.$store.state.camera.camera4.url
          new_monitor_flag_data = this.$store.state.camera.camera4.monitor_flag
        }
        // monitor_id = this.$store.getters.fenceCamera
        // new_monitor_flag_data = this.$store.getters.monitorFlag
      } else {
        monitor_id = '1'
        new_monitor_flag_data = 0
      }
      const data = {
        'pointList': this.pointArray,
        'lineList': this.lineList,
        'draw_index': this.lineIndex,
        'typeList': this.colorArray,
        'monitor_id': monitor_id,
        'new_monitor_flag': new_monitor_flag_data,
        'linetype': this.form.type
      }
      const dataJson = JSON.stringify(data)
      // 0为update 1为insert
      if (data.new_monitor_flag === 0) {
        await postFenceList(dataJson).then(res => {
          console.log(res)
          if (res.status === 1) {
            this.$message({
              message: '更新成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: '数据表更新失败或无更新',
              type: 'error'
            })
          }
        })
      } else {
        await postFenceList(dataJson).then(res => {
          console.log(res)
          if (res.status === 1) {
            this.$message({
              message: '新增成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: '数据表新增失败或重复',
              type: 'error'
            })
          }
        })
      }
      // await this.$store.dispatch('camera/setMonitorFlag', false)
    },
    drawRectError: debounce(function() {
      this.$message.error('请选择正确的矩形区域')
    }, 100)
  }
}
</script>

<style scoped>

</style>
